import React, { PureComponent } from 'react';
import moment from 'moment';

import { Input, Select } from 'antd';

const { Option } = Select;

const getTime = (time, fromUnit, toUnit) => moment.duration(Number(time), fromUnit).as(toUnit);

export const timeUnits = [
  { name: '秒', value: 'seconds' },
  { name: '分钟', value: 'minutes' },
  { name: '小时', value: 'hours' },
  { name: '天', value: 'days' },
];

class PeriodInput extends PureComponent {
  state = {
    value: '',
    unit: 'seconds',
  };

  componentWillMount() {
    const { props } = this;
    if (props.value) {
      this.setState({
        unit: 'seconds',
        value: props.value,
      });
    }
  }

  componentWillReceiveProps(nextProps) {
    const { props } = this;
    if (props.value !== nextProps.value && !nextProps.value) {
      this.setState({
        unit: 'seconds',
        value: '',
      });
    } else {
      this.setState({
        unit: 'seconds',
        value: nextProps.value,
      });
    }
  }

  handleSelectChange = unitValue => {
    const { unit, value } = this.state;
    const newValue = value ? getTime(value, unit, unitValue) : '';
    this.setState({
      unit: unitValue,
      value: newValue,
    });
  };

  onChangeValue = e => {
    const { value } = e.target;
    const { unit } = this.state;
    const { onChange } = this.props;
    const seconds = getTime(value, unit, 'seconds');
    this.setState({ value });
    if (onChange) onChange(seconds);
  };

  render() {
    const { unit, value } = this.state;
    return (
      <Input
        value={value}
        onChange={this.onChangeValue}
        addonAfter={
          <Select style={{ width: 80 }} value={unit} onChange={this.handleSelectChange}>
            {timeUnits.map(t => (
              <Option key={t.value} value={t.value}>
                {t.name}
              </Option>
            ))}
          </Select>
        }
      />
    );
  }
}

export default PeriodInput;
